import axios, { AxiosError, type AxiosRequestHeaders, type AxiosResponse } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

/* 定义response对象的data接口 */
interface ResponseData<T> {
  code: number
  data: T
  message: string
}

// 配置新建一个 axios 实例
const service = axios.create({
  baseURL: '/kl',
  timeout: 500000
})
// 定义是否是越南的接口
let isVietName = false
// 添加请求拦截器
service.interceptors.request.use((config: any) => {
  const token = sessionStorage.getItem('Authorization')
  const lang = localStorage.getItem('language')

  if (token) {
    ;(config.headers as AxiosRequestHeaders).Authorization = token
  } else {
    ;(config.headers as AxiosRequestHeaders).Authorization = `309_token`
  }
  if (lang && lang !== 'undefined') {
    ;(config.headers as AxiosRequestHeaders)['Accept-Language'] = lang
  }
  return config
})

// 添加响应拦截器
service.interceptors.response.use(
  /* 约束一下response */
  (response: AxiosResponse<ResponseData<any>>) => {
    if (response.request.responseURL.includes('http://10.1.1.43:8889')) {
      isVietName = true
    } else {
      isVietName = false
    }
    let res = response.data as any
    if (res.code === 3) {
      ElMessage.warning('登录超时请重新登录')
      sessionStorage.removeItem('Authorization')
      setTimeout(() => {
        window.location.href = '/login'
      }, 1000)
    }
    if (res.code === 200) {
      res.isVietName = isVietName
      return res.data
    } else {
      return res
    }
  }
)

export default service
